﻿#ifndef TCPSERVERDEMOD_H
#define TCPSERVERDEMOD_H

#include <QObject>
#include <QThread>
#include <QTimerEvent>

#include <net/listener.h>
#include <net/netreading.h>

using namespace QtSocket;
namespace QtSocket{
class NetWriting;
class TcpServer;
}
/**
 * @brief The TcpServerTest class 表示tcp服务端演示类。
 */
class TcpServerDemo : public QObject,
        public ISessionListener
{
    Q_OBJECT
    /**
     * @brief The Reading class 表示Tcp读取类。
     */
    class Reading: public NetReading
    {

    public:
        Reading(QtSocket::TcpSession *ownerSession, TcpServerDemo *ownerTest);
        // TcpReading interface
    public:
        void onProc(const QByteArray &arry) override;
    private:
        QtSocket::TcpSession *m_ownerSession;
        TcpServerDemo *m_ownerTest;
    };

public:
    explicit TcpServerDemo(QObject *parent = nullptr);
    ~TcpServerDemo() override;

    /**
     * @brief start 启动服务端。
     * @param localAddress
     * @param port
     * @return
     */
    bool start(QHostAddress localAddress, int port);
    /**
     * @brief stop 停止服务端。
     */
    void stop();
signals:
    /**
     * @brief log_signal  消息的信号。
     * @param msg 消息内容。
     */
    void log_signal(QString msg);
    // ISessionListener interface
public:
    void onError(QAbstractSocket::SocketError error) override;
    void onStateChanged(QtSocket::TcpSession *session, bool connected) override;
    // QObject interface
protected:
    void timerEvent(QTimerEvent *event) override;
public slots:
    /**
     * @brief fulfil 写入反馈。
     * @param sender
     * @param size
     */
    void fulfil(QSharedPointer<QtSocket::NetWriting> sender, int size);
private:
signals:
    void stop_signal();
private slots:
    void stop_slot();
private:
    QtSocket::TcpServer *m_server;

    int m_timerID;
    QAtomicInt m_counter; // 数据写入计数器。

};

#endif // TCPSERVERDEMOD_H
